package com.eastcompeace;

import java.util.Arrays;

import org.apache.cxf.Bus;
import org.apache.cxf.annotations.Provider;
import org.apache.cxf.endpoint.Server;
import org.apache.cxf.jaxrs.JAXRSServerFactoryBean;
import org.apache.cxf.jaxrs.swagger.Swagger2Feature;
import org.apache.cxf.transport.servlet.CXFServlet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.eastcompeace.controller.UserController;
import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider;

import io.swagger.config.ScannerFactory;
import io.swagger.jaxrs.config.BeanConfig;
import io.swagger.models.Swagger;
import io.swagger.models.parameters.HeaderParameter;

@Configuration
public class CxfConfig {

	@Autowired
	private Bus bus;

	@Bean
	public Server rsServer() {
		final JAXRSServerFactoryBean endpoint = new JAXRSServerFactoryBean();
		endpoint.setProviders(Arrays.asList(new JacksonJsonProvider(), new InvokeFaultExceptionMapper()));
		endpoint.setBus(bus);
		endpoint.setAddress("/");
		endpoint.setServiceBeans(Arrays.<Object>asList(userController()));
		endpoint.setFeatures(Arrays.asList(new ExtendedSwagger2Feature()));
		return endpoint.create();
	}

	@Bean
	public UserController userController() {
		return new UserController();
	}

	// The default address of CXF RESTfull API is /services to change the API
	// sub-directory from /services with /api or anything that you like
	@Bean
	public ServletRegistrationBean cxfServlet() {
		final ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new CXFServlet(), "/api/*");
		servletRegistrationBean.setLoadOnStartup(1);
		return servletRegistrationBean;
	}

	@Provider(value = Provider.Type.Feature, scope = Provider.Scope.Server)
	public static class ExtendedSwagger2Feature extends Swagger2Feature {
		@Override
		protected void addSwaggerResource(Server server, Bus bus) {
			super.addSwaggerResource(server, bus);

			BeanConfig config = (BeanConfig) ScannerFactory.getScanner();

			Swagger swagger = config.getSwagger();

			swagger.addParameter("tokens", new HeaderParameter());

		}
	}
}